package com.elangzhi.ssm.modules.friend.app;

import com.elangzhi.ssm.controller.json.Tip;
import com.elangzhi.ssm.model.Friend;
import com.elangzhi.ssm.model.User;
import com.elangzhi.ssm.modules.friend.services.FriendService;
import com.elangzhi.ssm.modules.user.services.UserService;
import com.elangzhi.ssm.tools.UUIDFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
* 通讯录 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/friend")
public class AppFriendController {

    /**
     * 获取好友申请列表
     * @param userId 用户id
     * @return 通讯录列表
     */
    @RequestMapping("applyListByUserId")
    @ResponseBody
    public List<Friend> applyListByUserId(Long userId){
        List<Friend> list = friendService.applyListByUserId(userId);
        for(Friend friend : list){
            friend.setFriendUser(userService.selectById(friend.getUserId()));
        }
        return list;
    }

    /**
     * 好友申请
     * @param userId 用户id
     * @param thinksId 对方thinksId
     * @return 成功状态
     * 1，添加失败
     * 2， 此账号未来过本平台
     */
    @RequestMapping("applyUserByThinksId")
    @ResponseBody
    public Tip applyUserByThinksId(Long userId,String thinksId){
        boolean isAdd = true;
        User user = userService.selectByThinksId(thinksId);
        if(user == null){
            return new Tip(2);
        }
        List<Friend> list = friendService.listByUserId(userId);
        for(Friend f : list){
            if(f.getFriendId() != null && f.getFriendId().equals(user.getId())){
                f.setFriendUserId(user.getId());
                f.setFriendStatus(2);
                try {
                    friendService.insert(f);
                    isAdd = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if(isAdd){
            Friend friend = new Friend();
            friend.setId(UUIDFactory.getLongId());
            friend.setUserId(userId);
            friend.setName(user.getName());
            friend.setPhone(user.getPhone());
            friend.setFriendUserId(user.getId());
            friend.setFriendStatus(2);
            try {
                friendService.insert(friend);
                return new Tip();
            } catch (Exception e) {
                System.out.println("使用thinksId申请添加好友");
                return new Tip(1);
            }
        }else{
            return new Tip();
        }
    }

    /**
     * 好友申请
     * @param friend 信息
     *               {
     *               id
     *               friendUserId
     *               }
     * @return 成功状态
     */
    @RequestMapping("applyUser")
    @ResponseBody
    public Tip applyUser(Friend friend){
        friend.setFriendStatus(2);
        try {
            friendService.updateById(friend);
            return new Tip();
        } catch (Exception e) {
            System.out.println("申请添加好友");
            return new Tip(1);
        }
    }


    /**
     * 处理好友申请
     * @param friend 信息
     *               {
     *               id
     *               friendStatus 0,1
     *               }
     * @return 成功状态
     */
    @RequestMapping("applyFriend")
    @ResponseBody
    public Tip applyFriend(Friend friend){
        boolean isAdd = false;
        Friend old = friendService.selectById(friend.getId());

        Long user1 = old.getUserId();
        Long user2 = old.getFriendUserId();
        Integer status = friend.getFriendStatus();

        //获取被申请列表
        List<Friend> list = friendService.applyListByUserId(user2);
        for(Friend f : list){
            if(f.getUserId().equals(user1)){
                f.setFriendStatus(status);
                if(status == 1){
                    f.setFriendUserId(user1);
                }
                try {
                    friendService.updateById(f);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        //被申请人自己的通讯录
        List<Friend> listAll = friendService.listByUserId(user2);
        for(Friend f : listAll){
            if(f.getFriendId() != null && f.getFriendId().equals(user1)){
                f.setFriendStatus(status);
                if(status == 1){
                    f.setFriendUserId(user1);
                }
                try {
                    friendService.updateById(f);
                    isAdd = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 如果自己通讯录里没有对方信息，则添加一条
        if(!isAdd){
            try {
                if(status == 1){
                    Friend newFriend = new Friend();
                    newFriend.setId(UUIDFactory.getLongId());
                    newFriend.setFriendStatus(1);
                    newFriend.setUserId(user2);
                    newFriend.setFriendUserId(user1);
                    User user = userService.selectById(user1);
                    newFriend.setName(user.getNickName());
                    newFriend.setPhone(user.getPhone());
                    friendService.insert(newFriend);
                }
                return new Tip();
            } catch (Exception e) {
                System.out.println("处理申请");
                return new Tip(1);
            }
        }else{
            return new Tip();
        }


    }

    /**
     * 获取用户通讯录
     * @param userId 用户id
     * @return 通讯录列表
     */
    @RequestMapping("listByUserId")
    @ResponseBody
    public List<Friend> listByUserId(Long userId){
        List<Friend> list = friendService.listByUserId(userId);
        for(Friend friend : list){
            if(friend.getFriendId() != null){
                friend.setFriendUser(userService.selectById(friend.getFriendId()));
            }
        }
        return list;
    }

    /**
     * 上传通讯录
     * @param userId 用户id
     * @param friends 通讯录
     * @return 成功状态
     */
    @RequestMapping("uploadFriend")
    @ResponseBody
    public Tip uploadFriend(Long userId,String friends){
        List<Friend> listAll = friendService.listByUserId(userId);
        if(friends == null){return new Tip(1);}
        // 清空非好友（登录多人手机时不会造成重复上传）
        for(Friend friend : listAll){
            try {
                if(friend.getFriendUserId() == null){
                    friendService.deleteById(friend.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        try {
            List<Friend> list = friendService.listByUserId(userId);
            for(String friendInfo : friends.split(";")){
                String[] infoArray = friendInfo.split(":");
                String name = infoArray[0];
                String phone = infoArray[1];
                if(name.isEmpty()){continue;}
                if(phone.isEmpty()){continue;}
                Friend friend = new Friend(UUIDFactory.getLongId(),name,phone,userId,0);
                if(!checkInfo(list,name,phone)){
                    try {
                        friendService.insert(friend);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 验证是否存在
     * @param list 通讯录list
     * @param name 姓名
     * @param phone 手机号
     * @return 结果
     */
    private boolean checkInfo(List<Friend> list, String name, String phone) {
        if(list == null && list.size() == 0){
            return false;
        }
        for(Friend friend : list){
            if(friend.getName().equals(name) && friend.getPhone().equals(phone)){
                return true;
            }
        }
        return false;
    }


    //---------------------------- property -------------------------------

    @Resource
    private FriendService friendService;


    @Resource
    private UserService userService;
}
